<script setup lang="ts">
import type { SongInfo } from '@/types/Playing'
import { ref, reactive , onMounted} from 'vue'
const emit = defineEmits(['onDrag'])
// 定义一个类，类似结构体
interface Position {
  x:number,
  progress:number
}
const position = reactive<Position>({ x: 0,progress:50})
const props = defineProps<{
  songInfo:SongInfo
}>()
// 初始化传过来的值
position.progress = (props.songInfo.progress / props.songInfo.total) * 100

// 获取目标html标签
const draggableElement = ref<HTMLElement | null>()
const progressElement = ref<HTMLElement | null>()

let isDragging = false
let offsetX = 0
const touchstart = (event:TouchEvent)=>{
  isDragging = true
  offsetX = event.touches[0].clientX - position.x
  // 监听鼠标移动touchmove，处理handleDragging
  document.addEventListener('touchmove', handleDragging)
  // 监听鼠标移动touchend，处理stopDragging
  document.addEventListener('touchend', stopDragging)
}

const handleDragging = (event:TouchEvent)=>{
  if (isDragging) {
    // 获取 偏移值，position为响应式数据，会自动更新
    position.x = event.touches[0].clientX - offsetX
    const screen_width = window.outerWidth * 0.92
    if (position.x < 0 ){
      position.x = 0
    }
    else if (position.x > screen_width){
      position.x = screen_width
    }
    position.progress = position.x / screen_width * 100
    emit('onDrag',position.progress)
  }
}

// let timer = 0
onMounted(()=>{
  // 设置进度 
  const screen_width = window.outerWidth * 0.92
  position.x = screen_width * position.progress / 100

  // 开启计时器
  // timer = setInterval(()=>{
  //   position.progress = props.songInfo.progress + 1
  //   position.x = screen_width * position.progress / 100
  //   console.log(position.progress)
  // },1000)
})

// onBeforeMount(()=>{
//   clearInterval(timer)
//   timer = 0
// })


const stopDragging = ()=>{
  isDragging = false
  document.removeEventListener('touchmove', handleDragging)
  document.removeEventListener('touchend', stopDragging)
}
</script>

<template>
  <div class="content">
    <div class="progress-bg">
      <div class="progress" ref="progressElement" :style="{width:position.progress+'%'}">

      </div>
    </div>

    <span class="dot" @touchstart="touchstart" ref="draggableElement" :style="{left:position.progress+'%'}">

    </span>
  </div>
</template>

<style lang="scss" scoped>
.content {
  position: absolute;
  background-color: transparent;
  width: 92vw;
  height: 3vw;
  margin-left: 4vw;
  margin-top: 10vw;
}

.progress-bg {
  position: relative;
  left: 0;
  right: 0;
  top: 1vw;
  bottom: 1vw;
  width: 100%;
  height: 1vw;
  background-color: #333;
}

.progress {
  //width: 50%;
  width: 0;
  height: 100%;
  background-color: #fff;
  border-radius: 0.5vw;
}

.dot {
  position: relative;
  //left: 50%;
  top: -2vw;
  bottom: 0;
  display: inline-block;
  width: 3vw;
  height: 3vw;
  background-color: #fff;
  border-radius: 1.5vw;
}
</style>